import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/models/Member.dart';
import 'package:kkhousekeep/net/authorization_connect.dart';
import 'package:kkhousekeep/page/home/home_main_page.dart';
import 'package:kkhousekeep/page/login/login_controller.dart';
import 'package:kkhousekeep/page/me/me_controller.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';
import 'package:kkhousekeep/tools/shared_preferences.dart';

import '../../net/respnse_code.dart';
import '../../tools/toast_util.dart';
import '../../widget/dialog/custom_dialog.dart';
import '../public/take_picture_screen.dart';

class InformationPageController extends GetxController {
  ///房间id
  final int roomId;

  ///社区id
  final int communityId;

  ///缓存图片路径
  var cacheImagePath = "".obs;

  ///网络图片路径
  late String netImagePath;

  ///名称
  var name = "".obs;

  ///电话号码
  var phone = "".obs;

  ///证件号码
  var certificateNumber = "".obs;

  ///证件类型
  var certificateType = IdCardType.identityCard.obs;

  ///经过转换的入住时间
  var entryDate = "".obs;

  ///实际的入住时间
  late DateTime enterTime;

  ///是否置灰
  var isAsh = true.obs;

  var useType = UserType.tenant.obs;

  late AuthorizationConnect connect;

  @override
  void onInit() {
    connect = Get.find<AuthorizationConnect>();
    _loadData();
    super.onInit();
  }

  InformationPageController({required this.communityId, required this.roomId});

  ///构建证件类型自建
  void buildCertificateWidget() {
    Get.bottomSheet(
      CustomDialog.customCupertinoActionSheet(
        [
          CupertinoActionSheetActionModel(IdCardType.identityCard.description,
              () {
            updateCertificateType(IdCardType.identityCard);
          }),
          CupertinoActionSheetActionModel(IdCardType.passport.description, () {
            updateCertificateType(IdCardType.passport);
          }),
          CupertinoActionSheetActionModel(
              IdCardType.permitForProceedingToHongKongAndMacao.description, () {
            updateCertificateType(
                IdCardType.permitForProceedingToHongKongAndMacao);
          }),
          CupertinoActionSheetActionModel(
              IdCardType.mainlandTravelPermitForTaiwanResidents.description,
              () {
            updateCertificateType(
                IdCardType.mainlandTravelPermitForTaiwanResidents);
          })
        ],
      ),
    );
  }

  ///构建时间选择器
  void buildDatePick() {
    FocusManager.instance.primaryFocus?.unfocus();
    Get.bottomSheet(
      CustomDialog.dataPicker(
        (dateTime) {
          updateDateTime(dateTime);
        },
      ),
    );
  }

  ///构建照相页面
  void buildTakePhotoScreen() {
    FocusManager.instance.primaryFocus?.unfocus();
    Get.to(
      TakePictureScreen(
        photoPathCallBack: (model) {
          cacheImagePath.value = model.cachePath;
          netImagePath = model.netPath!;
          observeText();
        },
      ),
    );
  }

  ///构建展示图片节目
  void buildShowPhotoScreen() {
    FocusManager.instance.primaryFocus?.unfocus();
    Get.to(
      () => DisplayPictureScreen(
        imagePath: cacheImagePath.value,
        isShowRetake: false,
      ),
    );
  }

  ///更新信息
  void updateInformation(String content, OwnerInformationType type) {
    if (type == OwnerInformationType.name) {
      name.value = content;
      observeText();
      return;
    }
    if (type == OwnerInformationType.certificateNumber) {
      certificateNumber.value = content;
      observeText();
      return;
    }
    if (type == OwnerInformationType.imagePath) {
      cacheImagePath.value = content;
      observeText();
      return;
    }
  }

  ///更新证件类型
  void updateCertificateType(IdCardType cardType) {
    certificateType.value = cardType;
    Get.back();
  }

  ///更新时间
  void updateDateTime(DateTime dateTime) {
    entryDate.value = "${dateTime.year}年${dateTime.month}月${dateTime.day}日";
    enterTime = dateTime;
    observeText();
  }

  ///观察文本
  void observeText() {
    if (name.isNotEmpty &&
        certificateNumber.isNotEmpty &&
        cacheImagePath.isNotEmpty &&
        entryDate.isNotEmpty) {
      isAsh.value = false;
      return;
    }
    isAsh.value = true;
  }

  ///上传信息
  Future<void> submitInformation() async {
    if (isAsh.value) {
      return;
    }
    DialogUtil.showNetworkLoading();
    var response = await connect.submitInformation(
        phone: phone.value,
        name: name.value,
        iDCardType: certificateType.value.value,
        iDCard: certificateNumber.value,
        enterTime: enterTime.toString(),
        image: netImagePath,
        roomID: roomId,
        cID: communityId);
    DialogUtil.dismiss();
    if (response == null) {
      return;
    }
    if (response.code == ResponseCode.success) {
      ToastUtils.showToast(tip: "已提交物业进行认证");
      await Get.offAll(
        () => HomeMainPage(
          index: 1,
          userType: useType.value,
        ),
      )?.whenComplete(() {
        Get.find<MeController>().onInit();
      });
      return;
    }
    DialogUtil.showNetworkFail();
  }

  Future<void> _loadData() async {
    var savedPhone = await getSp().getPhone();
    phone.value = savedPhone;
    var savedUserType = await getSp().getUserType();
    useType.value = savedUserType;
  }
}

///信息类型
enum OwnerInformationType {
  name,
  phone,
  certificateNumber,
  imagePath,
}
